import Cfg from './config.js';
import Cry from './crypto.js';
import Msg from './message.js';
import Nav from './navigation.js';
import Ext from './extend.js';

const DebugUrl = true;//是否打印URL信息

function objectToParamString (paramObj) {
  if (!paramObj) {
    return ''
  }
  let paramList = []
  Object.keys(paramObj) && Object.keys(paramObj).forEach(key => {
    let val = paramObj[key]
    if (val instanceof Array) {
      val.forEach(_val => {
        paramList.push(key + '=' + _val)
      })
    } else {
      paramList.push(key + '=' + val)
    }
  })
  return paramList.join('&')
}

async function _post(url,data,hook,success,fail) {
	return await _http('POST',url,data,success,hook,fail);
}

async function _get (url,data,hook,success,fail){
	return await _http('GET',url,data,success,hook,fail);
}

//网络请求
async function _http(type,url,data,success,hook,fail){
	let me = this;
	// // #ifdef H5
		
	// 	var bsc =  await me.He.bscInit();
	// 	console.log(!bsc._client)
	// 	if(!bsc._client){
	// 		window.location.href = 'http://www.baidu.com';
	// 		return;
	// 	} 
	// // #endif
	let address = Cfg.token();
	// let address = 'test';
	let lang = Ext.getLang();		
	let plat = '';
	//#ifdef H5
		plat = 'h5'
	//#endif
	//#ifdef APP-PLUS
		plat = 'app'
	//#endif
	//#ifdef MP-WEIXIN
		plat= 'xcx'
	//#endif		
	if(data.address){
		data = Object.assign({lang:lang,platform:plat}, data); 	
	}else{
		data = Object.assign({token:address,lang:lang,platform:plat}, data); 	
	}
	//console.log(Cfg.cfg.root+url)
	//console.log(data)
	if(DebugUrl)
	console.log(Cfg.cfg.root + url + '?' + objectToParamString(data))
	
	let response = {}	
	
	try{
		response = await uni.request({
			url:Cfg.cfg.root+url,
			data:data,		
			dataType:"json",
			method:type,		
			header:{'content-type':'application/x-www-form-urlencoded'}
		})
	}catch(err){
		response = err;
	}
	
	let errMsg = response[0] && response[0].errMsg || '';
	let res = response || {};
	if(errMsg!=''){
		Msg.Fail('网络请求出错:'+errMsg)
		return false; 
	}
	// if (res.statusCode !== 200) {
	// 	Msg.Fail('网络请求出错:'+url)
	// 	return false;          
	// }	
	let ret = null;	
	 res = res[1];
	if(Cfg.cfg.encrypt){//加密
		try{
			ret = Cry.secret(res.data,true);
		}catch(e){
			Msg.Fail('加密密钥不正确')										
			return false;
		}				
		ret = JSON.parse(ret);
	}else{
		ret = res.data;
		console.log(res)
		if(typeof ret!=='object'){				 
			Msg.Fail('网络请求出错:'+url)
			return false;    
		}				 
	}	
	if(hook){
		success && success(ret);
		return ret;
	}		 
	if(ret.code == -10){			  
		Msg.Toast(ret.msg,()=>{
			Nav._to({url:Cfg.cfg.login_route,type:1});
		}); 
		return false;
	}
	if (ret.code == 0) {
		Msg.Toast(ret.msg);
		return false;			  
	}else{
		success && success(ret);
		return ret;
	} 
	/*		
	uni.request({
		url:Cfg.cfg.root+url,
		data:data,		
		dataType:"json",
		method:type,		
		header:{'content-type':'application/x-www-form-urlencoded'},
		success(res){	
			//console.log(res)
			if (res.statusCode !== 200) { 					
				Msg.Fail('网络请求出错:'+url)
				return false;          
			}	
			let data = null;	 
			if(Cfg.cfg.encrypt){//加密
				try{
					data = Cry.secret(res.data,true);
				}catch(e){
					Msg.Fail('加密密钥不正确')										
					return false;
				}				
				data = JSON.parse(data);
			}else{
				data = res.data;
				if(typeof data!=='object'){				 
					Msg.Fail('网络请求出错:'+url)
					return false;    
				}				 
			}
			//console.log(data)
			if(hook){
				success && success(data);
				return false;
			}		 
			if(data.code == -10){			  
				Msg.Toast(data.msg,()=>{Nav._to({url:Cfg.cfg.login_route,type:1});}); 
				return false;
			}
			if (data.code == 0) {
				Msg.Toast(data.msg);
				return false;			  
			}else{
				success && success(data);
			}       			  
		},
		fail(res){
			if(hook){
				fail && fail(res.errMsg);
			}else{
				Msg.Fail(res.errMsg);
				fail && fail(res);
			}
		},
		complete(res){
			//complete && complete(res);			
		} 
	})	
	
	//*/
	
}

module.exports = {    
	_get,
	_post,
	postRequest:_post
}